﻿using Esri.ArcGISRuntime.ArcGISServices;
using Esri.ArcGISRuntime.Geometry;
using Esri.ArcGISRuntime.Mapping;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace ColiyerWpfControl.Gis.GeoLayer
{
    public abstract class BaseTileLayer : ImageTiledLayer
    {
        public BaseTileLayer(int maxZoomLevel)
            : base(CreateTileInfo(maxZoomLevel), new Envelope(-20037507.0672, -20036018.7354, 20037507.0672, 20102482.4102, SpatialReferences.WebMercator))
        {
        }

        private static TileInfo CreateTileInfo(int maxZoomLevel)
        {
            var levels = new LevelOfDetail[maxZoomLevel];
            double resolution = 156543.03392800014;
            double scale = resolution * 96 * 39.37;

            for (int i = 0; i < levels.Length; i++)
            {
                levels[i] = new LevelOfDetail(i, resolution, scale);
                resolution /= 2;
                scale /= 2;
            }

            return new TileInfo(96, TileImageFormat.Png, levels, new MapPoint(-20037507.0672, 20037507.0672, SpatialReferences.WebMercator),
                                SpatialReferences.WebMercator, 256, 256);
        }
        protected abstract Task<byte[]> GetTileByteAsync(int level, int row, int column, CancellationToken cancellationToken);

        protected override async Task<ImageTileData> GetTileDataAsync(int level, int row, int column, CancellationToken cancellationToken)
        {
            byte[] tileData = await GetTileByteAsync(level, row, column, cancellationToken);
            if (tileData != null)
            {
                return new ImageTileData(level, row, column, tileData, "png");
            }
            return null;
        }
    }

}
